import base64
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import datetime, timedelta
import time
import xml.etree.ElementTree as ET
import re
import requests
import urllib3
from sql.sql_conn import Mysql_data
from sql.sql_state import insert_data, select_gun, update_duiwu

urllib3.disable_warnings()


class Conn(object):
    def __init__(self, username, password):
        self.UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
        self.headers_doc = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Content-Length': '11',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': '123.108.119.156',
            'Origin': 'https://123.108.119.156',
            'Referer': 'https://123.108.119.156/',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'same-origin',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': self.UserAgent,
            'sec-ch-ua': '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        self.username = username
        self.password = password
        # self.conn_login()

    # 主页
    def conn_doc(self):
        # doc
        url_doc = 'https://m518.mos077.com/'

        date_doc = {'detection': 'Y'}
        r = requests.post(url_doc, headers=self.headers_doc, data=date_doc, verify=False).text
        ver = re.findall('top.ver = \'(.*)\';', r)[0]
        iovation = re.findall('top.iovationKey = \'(.*)\';', r)[0]
        return ver, iovation

    # 登陆
    def conn_login(self):
        ver, auto = self.conn_doc()
        url_login = f'https://m518.mos077.com/transform.php?ver={ver}'
        userAgent = base64.b64encode(self.UserAgent.encode('utf-8')).decode('utf-8')
        date_login = {
            'p': 'chk_login',
            'langx': 'zh-cn',
            'ver': ver,
            'username': self.username,
            'password': self.password,
            'app': 'N',
            'auto': auto,  # 'CDAHZD',
            'blackbox': '',
            'userAgent': userAgent
        }
        session = requests.Session()
        s = session.post(url_login, data=date_login, headers=self.headers_doc, verify=False,timeout=10)
        s_txt = s.text
        # print(s_txt)
        root = ET.fromstring(s_txt)
        code_message = root.find('code_message').text
        msg = root.find('msg').text
        print(msg, code_message)
        uid = root.find('uid').text
        return ver, uid, session


class Date_conn(Mysql_data):
    def __init__(self, ver, uid, session):
        # self.ver, self.uid, self.session = Conn('ls488888', 'xy514868928')
        self.ver = ver
        self.uid = uid
        self.session = session
        self.url_all = f'https://m518.mos077.com/transform.php?ver={self.ver}'


    # 全比赛
    def date_all(self):
        date_a = {
            'uid': self.uid,
            'ver': self.ver,
            'langx': 'zh-cn',
            'p': 'get_game_list',
            'p3type': '',
            'date': '',
            'gtype': 'ft',
            'showtype': 'live',
            'rtype': 'rb',
            'ltype': '3',
            'filter': '',
            'cupFantasy': 'N',
            'sorttype': 'L',
            'specialClick': '',
            'isFantasy': 'N',
            'ts': int(time.time() * 1000),
        }
        ss_data = self.session.post(url=self.url_all, data=date_a, verify=False,timeout=10).text
        # print(ss_data)
        return ss_data

    def hg_handle(self, hg_data):
        root = ET.fromstring(hg_data)
        quan_daxiao = []
        ban_daxiao = []
        quan_ran = []
        ban_ran = []
        for ec in root.findall('ec'):
            game = ec.find('game')
            try:
                ecid = game.find('ECID').text.strip()  # 比赛Id
            except Exception as e:
                print(e, game.find('ECID').text)
                ecid = 1
            # lid = game.find('LID').text.strip()  # 联赛Id
            try:
                retimeset = game.find('RETIMESET').text.strip()[3:5]  # 比赛进行时间
            except Exception as e:
                print(e, 'retimeset')
                retimeset = '0'
            # now_time = game.find('DATETIME').text.strip()[:-1]  # 比赛开始时间
            # date_time = datetime.strptime(now_time, '%m-%d %H:%M')
            # now = date_time + timedelta(hours=12)
            # current_time = datetime.now()
            # if current_time > now:
            #     now += timedelta(hours=12)
            # now_time = '2024-' + now.strftime('%m-%d %H:%M')

            if retimeset == 'ME':
                retimeset = '45'
            elif retimeset == 'rt':
                retimeset = '-1'
            # timer = game.find('TIMER').text.strip()     # 比赛进行时间
            # if timer == '半场':
            #     timer = '45'
            league = game.find('LEAGUE').text  # 联赛名
            if '电竞足球' in league or '进球数' in league or '特别投注' in league:
                continue
            team_h = game.find('TEAM_H').text  # 主队名
            team_c = game.find('TEAM_C').text  # 客队名

            score_h = game.find('SCORE_H').text  # 主
            score_c = game.find('SCORE_C').text  # 客
            try:
                score = score_h + ":" + score_c
            except:
                score = score_h
            # 全场让球
            strong = game.find('STRONG').text
            try:
                ratio_re = str(game.find('RATIO_RE').text).replace(' ', '')  # 让球 0/0.5
            except:
                ratio_re = str(game.find('RATIO_R').text).replace(' ', '')  # 让球 0/0.5
            # print(ratio_re)
            # if ratio_re is None:
            #     continue
            # try:
            if ratio_re != '0':
                if 'H' in strong:
                    reh = '-' + str(ratio_re)
                    rec = '+' + str(ratio_re)
                else:
                    reh = '+' + str(ratio_re)
                    rec = '-' + str(ratio_re)
            else:
                reh = '0'
                rec = '0'
            # except Exception as e:
            #     print(e,strong)
            name = '全场让'
            try:
                ior_reh = round(float(game.find('IOR_REH').text), 2)  # 主陪率  0.62
                ior_rec = round(float(game.find('IOR_REC').text), 2)  # 客陪率  1.2
            except:
                ior_reh = '0'
                ior_rec = '0'

            # 全场大小
            # try:
            try:
                ratio_rouo = str(game.find('RATIO_ROUO').text).replace(' ', '')  # 大小名 O3.5
            except:
                ratio_rouo = str(game.find('RATIO_OUO').text).replace(' ', '')  # 大小名 O3.5
            rouh = '小'
            rouc = '大'
            name_2 = '全场大小'
            try:
                ior_rouh = round(float(game.find('IOR_ROUH').text), 2)  # 小陪率
                ior_rouc = round(float(game.find('IOR_ROUC').text), 2)  # 大陪率
            except:
                ior_rouc = '0'
                ior_rouh = '0'
            # except Exception as e:
            #     print("ratio_rouo",e,ratio_rouo)
            q_ran = self.time_get, league, retimeset, score, team_h, team_c, name, team_h, reh, ior_reh, team_c, rec, ior_rec, self.time_time, ecid
            q_da = self.time_get, league, retimeset, score, team_h, team_c, name_2, rouc, ratio_rouo, ior_rouc, rouh, ratio_rouo, ior_rouh, self.time_time, ecid
            quan_daxiao.append(q_da)
            quan_ran.append(q_ran)
            # print(q_da)
            # print(q_ran)
            if int(retimeset) < 45:
                # 半让球
                hstrong = game.find('HSTRONG').text
                try:
                    ratio_hre = str(game.find('RATIO_HRE').text).replace(' ', '')  # 让球 0/0.5
                except:
                    ratio_hre = str(game.find('RATIO_HR').text).replace(' ', '')  # 让球 0/0.5
                # print(ratio_hre)
                # if ratio_hre == None:
                #     continue
                # try:
                if ratio_hre != '0':
                    if 'H' in hstrong:
                        hreh = '-' + str(ratio_hre)
                        hrec = '+' + str(ratio_hre)
                    else:
                        hreh = '+' + str(ratio_hre)
                        hrec = '-' + str(ratio_hre)
                else:
                    hreh = '0'
                    hrec = '0'
                # except Exception as e:
                #     print('ratio_hre', e,hstrong)
                try:
                    ior_hreh = round(float(game.find('IOR_HREH').text), 2)  # 主陪率  0.62
                    ior_hrec = round(float(game.find('IOR_HREC').text), 2)  # 客陪率  1.2
                except:
                    ior_hreh = '0'
                    ior_hrec = '0'
                hname = '上半场让'
                # 半大小
                try:
                    ratio_hrouo = str(game.find('RATIO_HROUO').text).replace(' ', '')  # 大小名 O3.5
                except:
                    ratio_hrouo = str(game.find('RATIO_HOUO').text).replace(' ', '')  # 大小名 O3.5
                hrouh = '小'
                hrouc = '大'
                try:
                    ior_hrouh = round(float(game.find('IOR_HROUH').text), 2)  # 小陪率
                    ior_hrouc = round(float(game.find('IOR_HROUC').text), 2)  # 大陪率
                except:
                    ior_hrouh = '0'
                    ior_hrouc = '0'
                hname_2 = '上半场大小'

                b_ran = self.time_get, league, retimeset, score, team_h, team_c, hname, team_h, hreh, ior_hreh, team_c, hrec, ior_hrec, self.time_time, ecid
                b_da = self.time_get, league, retimeset, score, team_h, team_c, hname_2, hrouc, ratio_hrouo, ior_hrouc, hrouh, ratio_hrouo, ior_hrouh, self.time_time, ecid
                ban_ran.append(b_ran)
                ban_daxiao.append(b_da)

        if len(quan_daxiao) != 0:
            n1 = insert_data("hg")
            self.run_sql(n1, quan_daxiao)
        if len(ban_daxiao) != 0:
            n2 = insert_data("hg_ban")
            self.run_sql(n2, ban_daxiao)
        if len(quan_ran) != 0:
            n3 = insert_data("hg_ran")
            self.run_sql(n3, quan_ran)
        if len(ban_ran) != 0:
            n4 = insert_data("hg")
            self.run_sql(n4, ban_ran)

    def hg_duiwu(self, hg_data, fbbb):
        if fbbb=='bb':
            bisai_get_bb = 'bisai_get_fb'
            BB_game_id = 'FB_game_id'
        else:
            bisai_get_bb = 'bisai_get_bb'
            BB_game_id = 'BB_game_id'

        root = ET.fromstring(hg_data)
        duiwu_all = []
        hg_get_duiwu_sql = select_gun('game_id', bisai_get_bb)  # "SELECT game_id FROM bisai_get_bb"
        hg_get_duiwu = self.run_sql(hg_get_duiwu_sql)  # bisai_get_bb
        hg_get_duiwu = [i[0] for i in hg_get_duiwu]

        hg_duiwu_sql = select_gun(BB_game_id, 'bisai_fb_bb_duiwu')  # "SELECT BB_game_id FROM bisai_fb_bb_duiwu"
        hg_duiwu = self.run_sql(hg_duiwu_sql)  # bisai_fb_bb_duiwu
        hg_duiwu = [i[0] for i in hg_duiwu]
        for ec in root.findall('ec'):
            game = ec.find('game')
            try:
                ecid = int(game.find('ECID').text.strip())  # 比赛Id
            except Exception as e:
                print(e, game.find('ECID').text)
                ecid = 100000001
            lid = game.find('LID').text.strip()  # 联赛Id
            try:
                retimeset = game.find('RETIMESET').text.strip()[3:5]  # 比赛进行时间
            except:
                retimeset = '0'
            now_time = game.find('DATETIME').text.strip()[:-1]  # 比赛开始时间
            an = game.find('DATETIME').text.strip()[10:]
            date_time = datetime.strptime(now_time, '%m-%d %H:%M')
            if an =='a':
                now = date_time + timedelta(hours=12)
            else:
                now = date_time + timedelta(hours=24)
            now_time = '2024-' + now.strftime('%m-%d %H:%M')

            if retimeset == 'ME':
                retimeset = '45'
            elif retimeset == 'rt':
                retimeset = '-1'
            # timer = game.find('TIMER').text.strip()     # 比赛进行时间
            # if timer == '半场':
            #     timer = '45'
            league = game.find('LEAGUE').text  # 联赛名
            if '电竞足球' in league or '进球数' in league or '特别投注' in league:
                continue
            team_h = game.find('TEAM_H').text  # 主队名
            team_c = game.find('TEAM_C').text  # 客队名

            # 比分
            score_h = game.find('SCORE_H').text  # 主
            score_c = game.find('SCORE_C').text  # 客
            try:
                score = score_h + ":" + score_c
            except:
                score = score_h

            hgduiwu = now_time, league, team_h, team_c, score, retimeset, ecid, lid
            # print(hg_get_duiwu)
            # print(hgduiwu)
            # print(ecid)
            if ecid not in hg_get_duiwu and hgduiwu not in duiwu_all:
                if ecid not in hg_duiwu:
                    print("hg", hgduiwu)
                    duiwu_all.append(hgduiwu)

            if ecid in hg_get_duiwu:

                tal = 'info_score', 'current_game_time'
                data_tal = score, retimeset
                for k, v in zip(tal, data_tal):
                    sql = update_duiwu(bisai_get_bb, k, 'game_id') # f"UPDATE bisai_get_bb SET {k} =%s WHERE game_id=%s"
                    self.run_sql(sql, (v, ecid))


        if duiwu_all != []:
            sql1 = f"insert into {bisai_get_bb} (bisai_time, match_name, Team_name_1, Team_name_2,info_score, current_game_time, game_id, region_id) values(%s,%s,%s,%s,%s,%s,%s,%s)"
            self.run_sql(sql1, duiwu_all)
        print("HG OK")

    def hg_one(self, ecid, lid):
        date_one = {
            'uid': self.uid,
            'ver': self.ver,
            'langx': 'zh-cn',
            'p': 'get_game_more',
            'gtype': 'ft',
            'showtype': 'live',
            'ltype': '3',
            'isRB': 'Y',
            'lid': lid,
            'specialClick': '',
            'mode': 'NORMAL',
            'filter': 'Main',
            'ts': int(time.time() * 1000),
            'ecid': ecid,
        }
        ss_data = self.session.post(url=self.url_all, data=date_one, verify=False,timeout=10).text
        # print(ss_data)
        self.time_get = time.strftime("%Y-%m-%d %X", time.localtime())
        self.time_time = time.time()
        self.hg_handle_one(ss_data)
        # return ss_data

    def hg_handle_one(self, hg_data):
        root = ET.fromstring(hg_data)
        quan_daxiao = []
        ban_daxiao = []
        quan_ran = []
        ban_ran = []
        try:
            ecid = root.find('ecid').text  # 比赛Id
        except Exception as e:
            print(e, "root.find('ecid').text1")
            ecid = 1000000
        try:
            for game in root.findall('game'):
                # print(game.text)
                # print("1234546")
                try:
                    re_time = int(game.find('re_time').text.strip()[3:5])  # 比赛进行时间
                except:
                    re_time = -1

                if re_time == 'ME':
                    re_time = 45
                elif re_time == 'rt':
                    re_time = -1
                if not isinstance(re_time, int):
                    re_time = -1

                league = game.find('league').text  # 联赛名

                team_h = game.find('team_h').text  # 主队名
                team_c = game.find('team_c').text  # 客队名

                excluded_keywords = [
                    '点球', '加时'
                ]
                if all(keyword in team_c for keyword in excluded_keywords):

                    print(team_h)
                    continue

                score_h = game.find('score_h').text  # 主
                score_c = game.find('score_c').text  # 客
                try:
                    score = score_h + ":" + score_c
                except:
                    score = score_h
                # 全场让球
                strong = game.find('strong').text # 区分+-

                ratio_re = str(game.find('ratio_re').text).replace(' ', '')  # 让球 0/0.5

                if ratio_re != '0':
                    if 'H' in strong:
                        reh = '-' + str(ratio_re)
                        rec = '+' + str(ratio_re)
                    else:
                        reh = '+' + str(ratio_re)
                        rec = '-' + str(ratio_re)
                else:
                    reh = '0'
                    rec = '0'
                # except Exception as e:
                #     print(e,strong)

                name = '全场让'
                try:
                    ior_reh = round(float(game.find('ior_REH').text), 2)  # 主陪率  0.62
                    ior_rec = round(float(game.find('ior_REC').text), 2)  # 客陪率  1.2
                except:
                    ior_reh = '0'
                    ior_rec = '0'

                # 全场大小
                ratio_rouo = str(game.find('ratio_rouu').text).replace(' ', '')  # 大小名 O3.5
                rouh = '小'
                rouc = '大'
                name_2 = '全场大小'
                try:
                    ior_rouh = round(float(game.find('ior_ROUH').text), 2)  # 小陪率
                    ior_rouc = round(float(game.find('ior_ROUC').text), 2)  # 大陪率
                except:
                    ior_rouc = '0'
                    ior_rouh = '0'
                ptype = game.find('ptype').text

                if ptype is not None and '角球' in ptype:
                    name = '全场角让'
                    name_2 = '全场角球大小'
                    team_h = team_h[:-5]
                    team_c = team_c[:-5]
                if ptype is not None and '罚牌' in ptype:
                    name = '全场黄牌让'
                    name_2 = '全场黄牌大小'
                    team_h = team_h[:-5]
                    team_c = team_c[:-5]
                q_ran = self.time_get, league, re_time, score, team_h, team_c, name, team_h, reh, ior_reh, team_c, rec, ior_rec, self.time_time, ecid
                q_da = self.time_get, league, re_time, score, team_h, team_c, name_2, rouc, ratio_rouo, ior_rouc, rouh, ratio_rouo, ior_rouh, self.time_time, ecid
                quan_daxiao.append(q_da)
                quan_ran.append(q_ran)
                # print(q_da)
                # print(q_ran)

                if int(re_time) < 45:
                    # 半让球
                    hstrong = game.find('hstrong').text
                    ratio_hre = str(game.find('ratio_hre').text).replace(' ', '')  # 让球 0/0.5

                    if ratio_hre != '0':
                        if 'H' in hstrong:
                            hreh = '-' + str(ratio_hre)
                            hrec = '+' + str(ratio_hre)
                        else:
                            hreh = '+' + str(ratio_hre)
                            hrec = '-' + str(ratio_hre)
                    else:
                        hreh = '0'
                        hrec = '0'

                    try:
                        ior_hreh = round(float(game.find('ior_HREH').text), 2)  # 主陪率  0.62
                        ior_hrec = round(float(game.find('ior_HREC').text), 2)  # 客陪率  1.2
                    except:
                        ior_hreh = '0'
                        ior_hrec = '0'
                    hname = '上半场让'
                    # 半大小
                    try:
                        ratio_hrouo = str(game.find('ratio_hrouo').text).replace(' ', '')  # 大小名 O3.5
                    except:
                        ratio_hrouo = str(game.find('RATIO_HOUO').text).replace(' ', '')  # 大小名 O3.5
                    hrouh = '小'
                    hrouc = '大'
                    try:
                        ior_hrouh = round(float(game.find('ior_HROUH').text), 2)  # 小陪率
                        ior_hrouc = round(float(game.find('ior_HROUC').text), 2)  # 大陪率
                    except:
                        ior_hrouh = '0'
                        ior_hrouc = '0'
                    hname_2 = '上半场大小'
                    if ptype is not None and '角球' in ptype:
                        hname = '上半场角让'
                        hname_2 = '上半角球大小'
                    if ptype is not None and '罚牌' in ptype:
                        hname = '上半黄牌让'
                        hname_2 = '上半黄牌大小'


                    b_ran = self.time_get, league, re_time, score, team_h, team_c, hname, team_h, hreh, ior_hreh, team_c, hrec, ior_hrec, self.time_time, ecid
                    b_da = self.time_get, league, re_time, score, team_h, team_c, hname_2, hrouc, ratio_hrouo, ior_hrouc, hrouh, ratio_hrouo, ior_hrouh, self.time_time, ecid
                    ban_ran.append(b_ran)
                    ban_daxiao.append(b_da)
                    # print(b_ran)
                    # print(b_da)
        except Exception as e:
            print('game', e)
        if len(quan_daxiao) != 0:
            n1 = insert_data("hg")
            self.run_sql(n1, quan_daxiao)
        if len(ban_daxiao) != 0:
            n2 = insert_data("hg_ban")
            self.run_sql(n2, ban_daxiao)
        if len(quan_ran) != 0:
            n3 = insert_data("hg_ran")
            self.run_sql(n3, quan_ran)
        if len(ban_ran) != 0:
            n4 = insert_data("hg")
            self.run_sql(n4, ban_ran)

    def hg_run(self, get_id):
        nn = 0
        try:
            with ThreadPoolExecutor(3) as t:
                for i_d in get_id:
                    time.sleep(0.1)
                    t.submit(self.hg_one, i_d[0], i_d[1])
            # for i_d in get_id:
            #     # print(i_d,i_d[0], i_d[1])
            #     self.hg_one(i_d[0], i_d[1])
                    nn += 1
        except Exception as e:
            print("ws", e)
        print(nn, "HG OK")


# if __name__ == '__main__':
#     con = Conn('zxc123zxcab', 'Zxc123123')
#     ver, uid, session = con.conn_login()
# #     while True:
# #         try:
#     da = Date_conn('ver', 'uid', 'session')
#     with open('one2.xml', 'r',encoding='utf8') as f:
#         ta = f.read()
#     # print(ta)
#     da.hg_handle_one(ta)
# #
#             alll = da.date_all()
#
#             da.hg_duiwu(alll)
#
#         except Exception as e:
#             print(e)
